package com.example.taobao;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class socketActivity extends AppCompatActivity implements Runnable{


    private List<Msg> msgList = new ArrayList<>();
//    private EditText editText;
//    private Button sendButton;
    private RecyclerView recyclerView;
    private MessageAdapter msgAdapter;

    private static final int SUCCESS = 0x123;
    private static final String HOST = "192.168.0.105"; //本机ip
    private static final int PORT = 12345;
    private TextView textShow;


    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;
    private String content = "";
    private StringBuilder builder = null;

    public Handler handler = new Handler(){
        public void handleMessage(Message msg){
            if(msg.what == SUCCESS){
                builder.append(content);
//                str=builder.toString();
                textShow.setText(builder.toString());
            }
        }
    };





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);
        initMsgs();


        builder = new StringBuilder();
        textShow = findViewById(R.id.textshow);

        EditText editText = (EditText)findViewById(R.id.enter);
        Button sendButton = (Button)findViewById(R.id.send);
        recyclerView =(RecyclerView)findViewById(R.id.chatroomRecyclerView);
        //布局排列方式
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        msgAdapter = new MessageAdapter(msgList);
        recyclerView.setAdapter(msgAdapter);


//        String str = editText.getText().toString();

//        sendButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //得到输入框中的内容
//                String content = editText.getText().toString();
//                //判断内容不是空的
//                if(!"".equals(content)){
//                    //将内容添加到单例中
//                    Msg msg = new Msg(content,Msg.TYPE_SENT);
//                    msgList.add(msg);
//                    //要求适配器重新刷新
//                    msgAdapter.notifyItemInserted(msgList.size()-1);
//                    //要求recyclerView布局将消息刷新
//                    recyclerView.scrollToPosition(msgList.size()-1);
//                    editText.setText("");
//                }
//            }
//        });

        //当程序一开始运行的时候就实例化Socket对象,与服务端进行连接,获取输入输出流
        //4.0以后不能再主线程中进行网络操作,所以需要另外开辟一个线程
        new Thread(){
            @Override
            public void run() {
                while(true) {


                    try {
                        //创建socket对象，指定主机地址和端口
                        socket = new Socket(HOST, PORT);
                        //                    //获取输入流
                        in = new BufferedReader(new InputStreamReader
                                (socket.getInputStream(), "UTF-8"));
                        //获取输出流
                        String msg = editText.getText().toString();
//                        String str1 = "123456444";
                        PrintWriter out = new PrintWriter(new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream())), true);
//                        out.println(str1);
                        out.println(msg);
                        Thread.sleep(10000);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();


//        new Thread(new Runnable(){
//            @Override
//            public void run() {
//                try {
//                    //输出流写入发送编辑框的信息并指定类型UTF-8，注意要加换行
////                    String str="TestString";
//
//                    String str = editText.getText().toString();
//                    if(socket==null) return;
//                    BufferedWriter outputStream=new BufferedWriter(
//                            new OutputStreamWriter(socket.getOutputStream()));
//                    outputStream.write(str);
//                    //输出流发送至服务器
//                    outputStream.flush();
//
//                } catch (UnsupportedEncodingException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//        }).start();


        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = editText.getText().toString();
                //判断内容不是空的
                if(!"".equals(content)){
                    //将内容添加到单例中
                    Msg msg = new Msg(content,Msg.TYPE_SENT);
                    msgList.add(msg);
                    //要求适配器重新刷新
                    msgAdapter.notifyItemInserted(msgList.size()-1);
                    //要求recyclerView布局将消息刷新
                    recyclerView.scrollToPosition(msgList.size()-1);
                    editText.setText("");
                }
//                String msg = editText.getText().toString();
                if(socket.isConnected()){
                    if(!socket.isOutputShutdown()){
//                        Toast.makeText(socketActivity.this, msg, Toast.LENGTH_SHORT).show();
//                        out.println(msg);
                    }
                }
            }
        });
        new Thread(socketActivity.this).start();


    }

    public void  initMsgs(){
        Msg msg1 = new Msg("你好！",Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("谢谢！你好。",Msg.TYPE_SENT);
        msgList.add(msg2);
        Msg msg3 = new Msg("加班么？",Msg.TYPE_RECEIVED);
        msgList.add(msg3);


    }



    @Override
    public void run() {
        try{
            //先让此线程睡眠一秒，让onCreate方法里的线程获取到socket
            Thread.sleep(1000);
            while (true){
                if(socket.isConnected()){ //判断socket是(返回true)否成功连接过
                    if(!socket.isInputShutdown()){  //判断socket是否关闭
                        if((content = in.readLine())!=null){
                            content+="\n";
                            handler.sendEmptyMessage(SUCCESS);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}